package com.android.flickr;

import java.io.IOException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.FlickrException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;

public class FlickrPickr extends Activity {
    
    public static final String PREFS_NAME = "MyPrefsFile";
    public static final String KEY_DEFAULT = "-1";
    
    //variable preferences
    public static final String KEY_TOKEN = "token";
    
    //static Flickr API application values
    public static final String USER_AUTH_URL = "http://www.flickr.com/services/auth/";
    public static final String AUTH_URL = "http://flickr.com/services/rest/";
	public static final String API_KEY = "d35a91cf46cbfc48c5dec2507c0c2821";
	public static final String API_SECRET = "d0d11ca8e6bb28b5"; //Shhhhhhhhh!
	public static final String PERMS = "w";
    
	//Activity keys for result
    private static final int ACTIVITY_AUTHENTICATE=1;
    private static final int ACTIVITY_META_DATA=2;
    private static final int ACTIVITY_SELECT_IMAGE=3;
    
    //for image file path
    private Cursor cursor; 
    private int column_index; 
    private String filePath = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_screen);
        
        //Just adding this stuff here so I can test that I'm getting the right stuff, yo.
        
        System.out.println("--------------flickr are go!-----------------------");
        
        //read in application preferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
        String miniAuthTok = settings.getString(KEY_TOKEN, KEY_DEFAULT);
        System.out.println("Some Mini Auth "+ miniAuthTok);

        //if there is not a key in preferences, start NoKey.class, otherwise go to main screen
        if(miniAuthTok.equals(KEY_DEFAULT)){
        	Intent i = new Intent(this, NoKey.class);
            startActivityForResult(i, ACTIVITY_AUTHENTICATE);
        }
        
      //upload button callback.
        Button uploadButton = (Button) findViewById(R.id.upload_button);
        uploadButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	//Intent i = new Intent(FlickrPickr.this, ChoosePicture.class);
                //startActivityForResult(i, ACTIVITY_META_DATA);
            	
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
                
            	//Intent i = new Intent(FlickrPickr.this, MetaData.class);
                //startActivityForResult(i, ACTIVITY_META_DATA);
            }
        });
        
        //settings button callback.
        Button settingsButton = (Button) findViewById(R.id.settings_button);
        settingsButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Intent i = new Intent(FlickrPickr.this, NoKey.class);
                startActivityForResult(i, ACTIVITY_AUTHENTICATE);
            }
        });
        
        //about button callback.
        Button aboutButton = (Button) findViewById(R.id.about_button);
        aboutButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Intent j = new Intent(FlickrPickr.this,About.class);
                startActivity(j);
            }
        });
        
        //exit button callback.  Quits program
        Button exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	finish();
            }
        });
 
    }
    
    @Override
    /*
     * Called when an activity finishes
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        switch(requestCode) {
        	case ACTIVITY_AUTHENTICATE:
        		if(resultCode == RESULT_OK){
        			Bundle extras = intent.getExtras();
        			
        			//get mini token string from bundle
            		String fullTok = extras.getString(KEY_TOKEN);
            		System.out.println("Token We Be Lookin At---> "+ fullTok);
        			//add mini token string to preferences
            		SharedPreferences settings = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
    				SharedPreferences.Editor editor = settings.edit();
    				editor.putString(KEY_TOKEN, fullTok);
    				
    				// Don't forget to commit your edits!!!
    				editor.commit();
        		}
        		
        	break;
        	case ACTIVITY_SELECT_IMAGE:
        		
        		if(resultCode == RESULT_OK){
        			//get the file path of the image that the user selected
        			Uri selectedImage = intent.getData();
        			String [] proj={MediaStore.Images.Media.DATA}; 
        			
        			cursor = managedQuery(selectedImage,proj,null,null,null);
        			column_index = cursor.getColumnIndexOrThrow(proj[0]); 
        			cursor.moveToNext();
        			filePath = cursor.getString(column_index);
        			
        			System.out.println("image filepath = "+filePath);
        			
        			//start meta data activity
        			Intent i = new Intent(FlickrPickr.this, MetaData.class);
                    startActivityForResult(i, ACTIVITY_META_DATA);
        			
        		}
        	break;
        	case ACTIVITY_META_DATA:
        		if(resultCode == RESULT_OK){
        			//get variables from bundle
        			Bundle extras = intent.getExtras();
        			String title = extras.getString("title");
        			String description = extras.getString("description");
        			// --- get more meta data if necessary --- 
        			
        			SharedPreferences settings = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
        	        String token = settings.getString(KEY_TOKEN, KEY_DEFAULT);
        			
        			//run flickr api uploader method
        			flickrTalkr talker = new flickrTalkr();
        			try{
						talker.uploadPhoto(filePath, title, description, token);
					} catch (IOException e) {
						e.printStackTrace();
					} catch (FlickrException e) {
						e.printStackTrace();
					} catch (SAXException e) {
						e.printStackTrace();
					}
        			
        		}
        	break;
        }
    }
}